/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SubsistemaFinanzas;

import clienteSandraParada.Login;
import java.awt.Color;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import service.Convenio;

/**
 *
 * @author Daniels
 */
public class Convenios extends javax.swing.JPanel {

    static Long id;
    service.Convenio convenio;
    static String valorNuevo;
    static String valorAnterior;

    /**
     * Creates new form ContenidoCaja
     */
    public Convenios() {
        initComponents();
        valorNuevo = "";
        valorAnterior = "";
        cargarTablaConvenios((java.util.List<service.Convenio>) listarConvenios());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dialogoEliminarConvenio = new javax.swing.JDialog();
        jPanel8 = new javax.swing.JPanel();
        etiquetaEliminar = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        botonSiEliminar = new javax.swing.JButton();
        botonNoEliminar = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tablaConvenios = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        jPanel6 = new javax.swing.JPanel();
        etiquetaMensajeria = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        dialogoEliminarConvenio.setTitle("Eliminar paciente");
        dialogoEliminarConvenio.setMinimumSize(new java.awt.Dimension(527, 190));
        dialogoEliminarConvenio.setModal(true);
        dialogoEliminarConvenio.setResizable(false);

        etiquetaEliminar.setText("¿Confirma que desea enviar a la papelera el convenio seleccionado?");

        jLabel20.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/Papelera.png"))); // NOI18N

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel20)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(etiquetaEliminar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel20)
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(etiquetaEliminar)))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        botonSiEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png"))); // NOI18N
        botonSiEliminar.setText("Si");
        botonSiEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSiEliminarActionPerformed(evt);
            }
        });

        botonNoEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        botonNoEliminar.setText("No");
        botonNoEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonNoEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout dialogoEliminarConvenioLayout = new javax.swing.GroupLayout(dialogoEliminarConvenio.getContentPane());
        dialogoEliminarConvenio.getContentPane().setLayout(dialogoEliminarConvenioLayout);
        dialogoEliminarConvenioLayout.setHorizontalGroup(
            dialogoEliminarConvenioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, dialogoEliminarConvenioLayout.createSequentialGroup()
                .addContainerGap(214, Short.MAX_VALUE)
                .addComponent(botonSiEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonNoEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        dialogoEliminarConvenioLayout.setVerticalGroup(
            dialogoEliminarConvenioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dialogoEliminarConvenioLayout.createSequentialGroup()
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dialogoEliminarConvenioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonSiEliminar)
                    .addComponent(botonNoEliminar))
                .addGap(0, 15, Short.MAX_VALUE))
        );

        setPreferredSize(new java.awt.Dimension(953, 603));

        jPanel5.setBackground(new java.awt.Color(255, 255, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1), "Convenios", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 36))); // NOI18N

        jLabel4.setText("Buscar ");

        tablaConvenios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Rut", "Nombre", "Porcentaje", "Forma de pago"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaConvenios.getTableHeader().setReorderingAllowed(false);
        tablaConvenios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaConveniosMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(tablaConvenios);

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addGap(728, 728, 728)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane4)
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
                .addGap(59, 59, 59))
        );

        jPanel6.setBackground(new java.awt.Color(255, 255, 255));

        etiquetaMensajeria.setText("Área de mensajería");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(etiquetaMensajeria, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(334, 334, 334))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(etiquetaMensajeria, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
        );

        jPanel7.setBackground(new java.awt.Color(255, 255, 255));

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/Edit.png"))); // NOI18N
        jButton2.setText("Modificar");
        jButton2.setMargin(new java.awt.Insets(2, 4, 2, 6));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/delete_32x32x32.png"))); // NOI18N
        jButton3.setText("Eliminar");
        jButton3.setMargin(new java.awt.Insets(2, 4, 2, 6));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/Previsualizar.png"))); // NOI18N
        jButton4.setText("Ver");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/Previsualizar.png"))); // NOI18N
        jButton1.setText("Ver ordenes de derivaciones");
        jButton1.setMaximumSize(new java.awt.Dimension(73, 43));
        jButton1.setMinimumSize(new java.awt.Dimension(73, 43));
        jButton1.setPreferredSize(new java.awt.Dimension(73, 43));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel7Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton2, jButton3, jButton4});

        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jPanel7Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton2, jButton3, jButton4});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
        if (p.isModificarConvenio()) {
            //modificar convenio
            this.normalizarMensajeria();
            int[] filasSelec = tablaConvenios.getSelectedRows();
            if (filasSelec.length == 1) {
                int fila = filasSelec[0];
                convenio = buscarConvenio((String) this.tablaConvenios.getValueAt(fila, 0));
                /*se guarda el Id para saber que ficha clinica debo modificar
                en la base de datos*/
                id = convenio.getId();
                formularioConvenio formularioConvenio = new formularioConvenio(null, true, this);
                formularioConvenio.setTitle("Modificar Convenio");
                formularioConvenio.limpiarFormulario();
                formularioConvenio.llenarDatosFormulario(convenio);
                formularioConvenio.habilitarCampos(true);
                formularioConvenio.ocultarAsteriscosFormulario(false);
                formularioConvenio.configurarBotones("modificar");
                formularioConvenio.setLocationRelativeTo(null);
                formularioConvenio.setVisible(true);
            } else {
                this.etiquetaMensajeria.setText("Debe seleccionar solo una fila!");
                etiquetaMensajeria.setForeground(Color.red);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
        if (p.isEliminarConvenio()) {
            // Eliminar Convenio
            int[] filasSelec = tablaConvenios.getSelectedRows();
            if (filasSelec.length > 0) {
                if (filasSelec.length > 1) {
                    etiquetaEliminar.setText("¿Confirma que desea enviar a la papelera los convenios seleccionados?");
                } else if (filasSelec.length == 1) {
                    etiquetaEliminar.setText("¿Confirma que desea enviar a la papelera el convenio seleccionado?");
                }
                dialogoEliminarConvenio.setLocationRelativeTo(null);
                dialogoEliminarConvenio.setVisible(true);
            } else {
                etiquetaMensajeria.setText("No se ha seleccionado un convenio para eliminar");
                etiquetaMensajeria.setForeground(Color.red);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void botonSiEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSiEliminarActionPerformed
        // dialogo eliminar convenio
        int[] filasSelec = tablaConvenios.getSelectedRows();
        if (filasSelec.length == 1) {
            service.Convenio p = (service.Convenio) buscarConvenio(((String) tablaConvenios.getValueAt(filasSelec[0], 0)));
            p.setActivo(false);
            modificarConvenio(p);
            String valorNuevo = " Rut institución: " + p.getRutInstitucion();
            registrar(Login.getUser(), "Convenio", "Eliminó convenio" + p.getRutInstitucion(), "No aplica", valorNuevo);
        } else {
            for (int i = 0; i < filasSelec.length; i++) {
                service.Convenio p = (service.Convenio) buscarConvenio(((String) tablaConvenios.getValueAt(filasSelec[i], 0)));
                p.setActivo(false);
                modificarConvenio(p);
                String valorNuevo = " Rut institución: " + p.getRutInstitucion();
                registrar(Login.getUser(), "Convenio", "Eliminó convenio" + p.getRutInstitucion(), "No aplica", valorNuevo);
            }
        }
        this.cargarTablaConvenios((java.util.List<service.Convenio>) listarConvenios());
        this.dialogoEliminarConvenio.dispose();
    }//GEN-LAST:event_botonSiEliminarActionPerformed

    private void botonNoEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonNoEliminarActionPerformed
        // TODO add your handling code here:
        dialogoEliminarConvenio.dispose();
}//GEN-LAST:event_botonNoEliminarActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
        if (p.isVerConvenio()) {
            //Ver convenio seleccionado
            this.normalizarMensajeria();
            formularioConvenio formularioConvenio = new formularioConvenio(null, true, this);
            formularioConvenio.limpiarFormulario();
            formularioConvenio.setTitle("Ver Convenio");
            formularioConvenio.configurarBotones("imprimir");
            //Solo puede seleccionar una fila de la tabla de fichas principal
            int[] filasSelec = tablaConvenios.getSelectedRows();
            if (filasSelec.length == 1) {
                int fila = filasSelec[0];
                convenio = buscarConvenio((String) this.tablaConvenios.getValueAt(fila, 0));
                /*se guarda el Id para saber que ficha clinica debo modificar
                en la base de datos*/
                formularioConvenio.llenarDatosFormulario(convenio);
                formularioConvenio.habilitarCampos(false);
                formularioConvenio.configurarBotones("ver");
                formularioConvenio.ocultarAsteriscosFormulario(true);
                formularioConvenio.setLocationRelativeTo(null);
                formularioConvenio.setVisible(true);
            } else {
                etiquetaMensajeria.setText("Debe seleccionar solo una fila!");
                etiquetaMensajeria.setForeground(Color.red);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        this.normalizarMensajeria();
        int[] filasSelec = tablaConvenios.getSelectedRows();
        if (filasSelec.length == 1) {
            String rutInstitucion = (String) tablaConvenios.getValueAt(tablaConvenios.getSelectedRow(), 0);
            OrdenesDeDerivacion orden = new OrdenesDeDerivacion(rutInstitucion, null, true);
            orden.setLocationRelativeTo(null);
            orden.setVisible(true);
        } else {
            etiquetaMensajeria.setText("Debe seleccionar solo una fila!");
            etiquetaMensajeria.setForeground(Color.red);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void tablaConveniosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaConveniosMouseClicked
        //ver convenio
        DefaultTableModel modelo = (DefaultTableModel) this.tablaConvenios.getModel();
        int fila = this.tablaConvenios.rowAtPoint(evt.getPoint());
        if ((fila > -1) && evt.getClickCount() == 2) {
            this.normalizarMensajeria();
            formularioConvenio formularioConvenio = new formularioConvenio(null, true, this);
            formularioConvenio.limpiarFormulario();
            formularioConvenio.setTitle("Ver Convenio");
            formularioConvenio.configurarBotones("imprimir");
            //Solo puede seleccionar una fila de la tabla de fichas principal
            int[] filasSelec = tablaConvenios.getSelectedRows();
            if (filasSelec.length == 1) {
                int fi = filasSelec[0];
                convenio = buscarConvenio((String) this.tablaConvenios.getValueAt(fi, 0));
                /*se guarda el Id para saber que ficha clinica debo modificar
                en la base de datos*/
                formularioConvenio.llenarDatosFormulario(convenio);
                formularioConvenio.habilitarCampos(false);
                formularioConvenio.configurarBotones("ver");
                formularioConvenio.setLocationRelativeTo(null);
                formularioConvenio.setVisible(true);
            } else {
                etiquetaMensajeria.setText("Debe seleccionar solo una fila!");
                etiquetaMensajeria.setForeground(Color.red);
            }
        }
    }//GEN-LAST:event_tablaConveniosMouseClicked

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        //buscar convenio
        if (!jTextField1.getText().equals("")) {
            cargarTablaConvenios((java.util.List<service.Convenio>) listarConvenios());
            actualizarTablaBusqueda(jTextField1.getText());
        } else {
            cargarTablaConvenios((java.util.List<service.Convenio>) listarConvenios());
        }
        
    }//GEN-LAST:event_jTextField1KeyReleased

    public void actualizarTablaBusqueda(String buscar) {
        DefaultTableModel temp = (DefaultTableModel) tablaConvenios.getModel();
        for (int i = 0; i < temp.getRowCount(); i++) {
            if (!contienePalabra(buscar, temp, i)) {
                temp.removeRow(i);
                i--;
            }

        }
    }
    
    /**
     * @method que se encarga de buscar si una palabra buscada esta dentro de una columna de la tabla
     * @param buscar
     * @param temp
     * @param fila
     * @return
     */
    public boolean contienePalabra(String buscar, DefaultTableModel temp, int fila) {
        int coincidencias = 0;
        int j = 0;
        String buscarAux = buscar.toUpperCase();
        if (temp.getColumnName(0).equals("ID")) {
            j++;
        }
        for (int i = j; i < temp.getColumnCount(); i++) {
            String frase = (String) temp.getValueAt(fila, i);
            if ((frase.toUpperCase()).contains(buscarAux)) {
                coincidencias += 1; // existe una columna que coincide con la palabra buscada
            }
        }
        if (coincidencias == 0) {
            return false; // no existen coincidencias
        } else {
            return true;
        }
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonNoEliminar;
    private javax.swing.JButton botonSiEliminar;
    private javax.swing.JDialog dialogoEliminarConvenio;
    private javax.swing.JLabel etiquetaEliminar;
    public static javax.swing.JLabel etiquetaMensajeria;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextField jTextField1;
    public javax.swing.JTable tablaConvenios;
    // End of variables declaration//GEN-END:variables

    static void agregarConvenioBD(String rutConvenio, String formaPago, String fechaInicio, String fechaTermino, String porcentaje,
            String observacion, boolean activo) {
        try { // Call Web Service Operation
            service.ConvenioWSService service = new service.ConvenioWSService();
            service.ConvenioWS port = service.getConvenioWSPort();
            // TODO process result here
            valorNuevo = "Rut convenio: " + rutConvenio + "\n" + "Forma pago: " + formaPago + "\n" + "Fecha inicio: " + fechaInicio + "\n" + "Fecha termino: " + fechaTermino + "\n" + "Porcentaje: "
                    + porcentaje + "\n" + "Observación: " + observacion;
            registrar(Login.getUser(), "Convenio", "Agregó convenio: "+rutConvenio, "No aplica", valorNuevo);
            Long result = port.agregarConvenio(rutConvenio, formaPago, fechaInicio,
                    fechaTermino, porcentaje, observacion, activo);

        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
    }

    public void limpiarTabla() {
        DefaultTableModel temp = (DefaultTableModel) tablaConvenios.getModel();
        for (int i = tablaConvenios.getRowCount() - 1; i >= 0; i--) {
            temp.removeRow(i);
        }
    }

    public void cargarTablaConvenios(java.util.List<service.Convenio> con) {
        limpiarTabla();
        service.ConvenioWSService service = new service.ConvenioWSService();
        service.ConvenioWS port = service.getConvenioWSPort();
        //Obtiene las fichas clinicas almacenadas en la base de datos
        java.util.List<service.Convenio> convenios = con;
        for (int i = 0; i < convenios.size(); i++) {
            if (convenios.get(i).isActivo() == true) {
                int fila = this.tablaConvenios.getRowCount();
                DefaultTableModel modelo = (DefaultTableModel) this.tablaConvenios.getModel();
                modelo.addRow(new String[3]);
                for (int col = 0; col < this.tablaConvenios.getColumnCount(); col++) {
                    //buscar el nombre de la persona con la cual se realizo el convenio
                    service.ProfesionalExterno pro= (service.ProfesionalExterno) cargarProfesionalExterno(convenios.get(i).getRutInstitucion());
                    this.tablaConvenios.setValueAt(convenios.get(i).getRutInstitucion(), fila, 0);
                    this.tablaConvenios.setValueAt(pro.getNombres()+" "+pro.getApellidoPaterno()+" "+pro.getApellidoMaterno(), fila, 1);
                    this.tablaConvenios.setValueAt(convenios.get(i).getPorcentaje(), fila, 2);
                    this.tablaConvenios.setValueAt(convenios.get(i).getFormaPago(), fila, 3);
                }
            }
        }
    }

    private static Object cargarProfesionalExterno(java.lang.String rut) {
        service.ProfesionalExternoWSService service = new service.ProfesionalExternoWSService();
        service.ProfesionalExternoWS port = service.getProfesionalExternoWSPort();
        return port.cargarProfesionalExterno(rut);
    }
    
    public Date stringToDate(String strFecha) {
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd-MM-yyyy");
        Date fecha = null;
        try {
            fecha = formatoDelTexto.parse(strFecha);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return fecha;
    }

    static service.Convenio buscarConvenio(String rutConvenio) {
        service.ConvenioWSService service = new service.ConvenioWSService();
        service.ConvenioWS port = service.getConvenioWSPort();

        java.util.List<service.Convenio> convenios = port.listarConvenios();
        //buscar el convenio por el rut de la institucion o profesional
        for (int i = 0; i < convenios.size(); i++) {
            if (convenios.get(i).getRutInstitucion().equals(rutConvenio)) {
                return convenios.get(i);
            }
        }
        return null;
    }

    static void modificarConvenioBD(String rutConvenio, String formaPago,
            String fechaInicio, String fechaTermino, String porcentaje, String observacion, boolean activo) {
        try {
            service.ConvenioWSService service = new service.ConvenioWSService();
            service.ConvenioWS port = service.getConvenioWSPort();
            service.Convenio c=(service.Convenio) cargarConvenio(id);
            valorAnterior="Rut convenio: " + c.getRutInstitucion() + "\n" + "Forma pago: " + c.getFormaPago() + "\n" + "Fecha inicio: " + c.getFechaInicio() + "\n" + "Fecha termino: " + c.getFechaTermino() + "\n" + "Porcentaje: "
                    + c.getPorcentaje() + "\n" + "Observación: " +c.getObservacion();
            valorNuevo = "Rut convenio: " + rutConvenio + "\n" + "Forma pago: " + formaPago + "\n" + "Fecha inicio: " + fechaInicio + "\n" + "Fecha termino: " + fechaTermino + "\n" + "Porcentaje: "
                    + porcentaje + "\n" + "Observación: " + observacion;
            registrar(Login.getUser(), "Convenio", "Modificó convenio: "+rutConvenio, valorAnterior, valorNuevo);
            boolean resultado = port.modificarConvenio(id, rutConvenio, formaPago, fechaInicio,
                    fechaTermino, porcentaje, observacion, activo);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }

    }

    static Long registrarBitacora(java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(Login.getUser(), modulo, accion, valorAnterior, valorNuevo);
    }

    static void cambiarEtiqueta(String etiqueta) {
        etiquetaMensajeria.setText(etiqueta);
    }

    public void normalizarMensajeria() {
        etiquetaMensajeria.setText("");
        etiquetaMensajeria.setForeground(Color.black);
    }

    private static Object cargarPrivilegios(java.lang.String rut) {
        service.PrivilegiosWS_Service service = new service.PrivilegiosWS_Service();
        service.PrivilegiosWS port = service.getPrivilegiosWSPort();
        return port.cargarPrivilegios(rut);
    }

    public void modificarConvenio(service.Convenio convenio) {
        try {
            service.ConvenioWSService service = new service.ConvenioWSService();
            service.ConvenioWS port = service.getConvenioWSPort();
            boolean resultado = port.eliminarConvenio(convenio);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
    }

    private static java.util.List<service.Convenio> listarConvenios() {
        service.ConvenioWSService service = new service.ConvenioWSService();
        service.ConvenioWS port = service.getConvenioWSPort();
        return port.listarConvenios();
    }

    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }

    public service.ProfesionalExterno buscarProfesionalExterno(String rut) {
        service.ProfesionalExternoWSService service = new service.ProfesionalExternoWSService();
        service.ProfesionalExternoWS port = service.getProfesionalExternoWSPort();

        java.util.List<service.ProfesionalExterno> profesionales = port.listarProfesionalesExternos();
        //buscar paciente por el rut
        for (int i = 0; i < profesionales.size(); i++) {
            if (profesionales.get(i).getRut().equals(rut)) {
                return profesionales.get(i);
            }
        }
        return null;
    }

    private static Object cargarConvenio(java.lang.Long id) {
        service.ConvenioWSService service = new service.ConvenioWSService();
        service.ConvenioWS port = service.getConvenioWSPort();
        return port.cargarConvenio(id);
    }

}
